import { ElMessage, FormInstance } from 'element-plus';
import Sortable from 'sortablejs';
import { httpReqeustApi } from '/@/api/linxyun/base';
import { jsplumbDefaults, jsplumbMakeSource, jsplumbMakeTarget, jsplumbConnect } from '../config';
import EventHandler from '../cpns/eventHandler/index.vue';
import { LocationQuery } from 'vue-router';

interface IState {
	flowFunPiece: boolean;
	addFlowPieceData: Record<string, any>;
	addFlowPiecedialog: boolean;
}
export default function (
	dragFBToEventIndex: any,
	jsplumbData: Record<string, any>[],
	jsPlumbInstList: any[],
	funcPieceCalldialog: any,
	nodeTypeList: any,
	routeParams: LocationQuery
) {
	const httpRequest = httpReqeustApi();
	const state = reactive<IState>({
		flowFunPiece: true,
		addFlowPieceData: {
			FBName: '',
			Descption: '',
			Lang: '',
			OutputVars: '',
			InputVars: '',
			Remarks: '',
		},
		addFlowPiecedialog: false,
	});

	const leftNavRef = ref<InstanceType<typeof HTMLDivElement>>();
	const flowRefs = ref<InstanceType<typeof HTMLDivElement>>();
	const startEndFbRef = ref<InstanceType<typeof HTMLDivElement>>();
	const addFlowPieceRef = ref<FormInstance>();

	// 左侧功能块-初始化拖动
	const initSortable = (EditCallFB: any, FBCallRef: any) => {
		// console.log('initSortable', this.$refs.leftNavRefs)
		// console.log('initSortable', this.$refs.startEndFbRef)
		// 流程功能块
		console.log('jsplumbData', jsplumbData);
		console.log('leftNavRef', leftNavRef.value);
		Sortable.create(leftNavRef.value!, {
			group: {
				name: 'vue-next-admin-1',
				pull: 'clone',
				put: false,
			},
			animation: 0,
			sort: false,
			draggable: '.left-item',
			forceFallback: true,
			onEnd: (evt: any) => {
				const el = evt.originalEvent.path[0];
				console.log('el', el);
				const index = el.id.split('-')[1] - 1;
				console.log('index', index);
				dragFBToEventIndex.value = index; // 保存当前画布的索引
				console.log(el.id);
				const { fbname, descption, id, inputVars, lang, outputVars, remarks } = evt.clone.dataset;
				console.log('dataset', evt.clone.dataset);
				const { layerX, layerY, clientX, clientY } = evt.originalEvent;
				console.log('flowRefs', flowRefs.value);
				console.log(el);
				const { x, y, width, height } = el.getBoundingClientRect();
				console.log('target:', { x, y, width, height }, 'origin:', { layerX, layerY, clientX, clientY });
				console.log(clientX < x || clientX > width + x || clientY < y || y > y + height);
				if (clientX < x || clientX > width + x || clientY < y || y > y + height) {
					ElMessage({
						type: 'warning',
						message: '请把节点拖入到画布中',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				} else {
					try {
						const nodeList = jsplumbData[index].nodeList;
						EditCallFB.value = false;
						// 处理节点数据
						const node = {
							fbname: fbname + '-' + index + 1,
							left: `${layerX - 40}px`,
							top: `${layerY - 15}px`,
							class: evt.clone.dataset.class + '-flow',
							descption,
							id: fbname + '-' + index + 1,
							inputVars,
							lang,
							outputVars,
							remarks,
							CallFBID: nodeList[nodeList.length - 1].CallFBID * 1 + 1,
						};
						// 右侧视图内容数组
						jsplumbData[index].nodeList.push(node);
						// 如果上一个功能块是开始就自动连线
						if (jsplumbData[index].nodeList.length === 2 && jsplumbData[index].nodeList[0].fbname === 'start-fb') {
							jsplumbData[index].lineList.push({
								sourceId: 'start-fb-' + (index + 1),
								targetId: node.fbname,
								label: '',
							});
						}
						// 元素加载完毕时
						nextTick(() => {
							// 整个节点作为source或者target
							jsPlumbInstList[index].makeSource(node.fbname, jsplumbMakeSource);
							// // 整个节点作为source或者target
							jsPlumbInstList[index].makeTarget(node.fbname, jsplumbMakeTarget, jsplumbConnect);
							// 设置节点可以拖拽（此处为id值，非class）
							jsPlumbInstList[index].draggable(node.fbname, {
								containment: 'parent',
								stop: (el) => {
									jsplumbData[index].nodeList.forEach((v) => {
										if (v.fbname === el.el.id) {
											// 节点x, y重新赋值，防止再次从左侧导航中拖拽节点时，x, y恢复默认
											v.left = `${el.pos[0]}px`;
											v.top = `${el.pos[1]}px`;
										}
									});
								},
							});
						});
						funcPieceCalldialog.value = true;
						const FBItem = { ...node };
						FBItem.inputVars = FBItem.inputVars.split(',').map((val) => ({ label: val, value: '' }));
						FBItem.outputVars = FBItem.outputVars.split(',');

						nextTick(() => {
							console.log('FBCallRef', FBCallRef.value, funcPieceCalldialog.value);
							FBCallRef.value.FBItem = FBItem;
						});
					} catch (e) {
						ElMessage({
							type: 'warning',
							message: '请把节点拖入到画布中',
							duration: BASE_API.MSG_SHOW_TIME,
						});
					}
				}
			},
		});

		// 开始结束拖动块-初始化拖动
		Sortable.create(startEndFbRef.value!, {
			group: {
				name: 'vue-next-admin-2',
				pull: 'clone',
				put: false,
			},
			animation: 0,
			sort: false,
			draggable: '.fb-node',
			forceFallback: true,
			onEnd: (evt: any) => {
				const nodeId = Math.random().toString(36).substr(2, 12);
				const el = evt.originalEvent.path[0];
				console.log('el', el);
				const index = el.id.split('-')[1] - 1;
				console.log(el.id);
				const { fbname, descption, id } = evt.clone.dataset;
				console.log('dataset', evt.clone.dataset);
				const { layerX, layerY, clientX, clientY } = evt.originalEvent;
				console.log('flowRefs', flowRefs.value);
				console.log(el);
				const { x, y, width, height } = el.getBoundingClientRect();
				console.log('target:', { x, y, width, height }, 'origin:', { layerX, layerY, clientX, clientY });
				if (clientX < x || clientX > width + x || clientY < y || y > y + height) {
					ElMessage({
						type: 'warning',
						message: '请把节点拖入到画布中',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				} else {
					try {
						// 处理节点数据
						const node = {
							fbname: fbname + '-' + index + 1,
							left: `${layerX - 40}px`,
							top: `${layerY - 15}px`,
							class: 'circle-flow',
							descption,
							id: fbname + '-' + index + 1,
						};

						const i = jsplumbData[index].nodeList.findIndex((node: Record<string, never>) => node.fbname === fbname);
						if (i !== -1) {
							ElMessage({
								type: 'warning',
								message: '当前画布已经存在该流程块',
								duration: BASE_API.MSG_SHOW_TIME,
							});
							return;
						}
						console.log('node:', node, jsPlumbInstList[index]);
						// 右侧视图内容数组
						jsplumbData[index].nodeList.push(node);
						// 元素加载完毕时
						nextTick(() => {
							// 整个节点作为source或者target
							jsPlumbInstList[index].makeSource(node.fbname, jsplumbMakeSource);
							// // 整个节点作为source或者target
							jsPlumbInstList[index].makeTarget(node.fbname, jsplumbMakeTarget, jsplumbConnect);
							// 设置节点可以拖拽（此处为id值，非class）
							jsPlumbInstList[index].draggable(node.fbname, {
								containment: 'parent',
								stop: (el: Record<string, any>) => {
									jsplumbData[index].nodeList.forEach((v: Record<string, any>) => {
										if (v.fbname === el.el.id) {
											// 节点x, y重新赋值，防止再次从左侧导航中拖拽节点时，x, y恢复默认
											v.left = `${el.pos[0]}px`;
											v.top = `${el.pos[1]}px`;
										}
									});
								},
							});
						});
						// this.funcPieceCalldialog = true
					} catch (e) {
						ElMessage({
							type: 'warning',
							message: '请把节点拖入到画布中',
							duration: BASE_API.MSG_SHOW_TIME,
						});
					}
				}
			},
		});
	};
	// 查询功能块
	const handleQueryFlowPiece = async (FBType: number): Promise<Record<string, any>[]> => {
		const data = { FBType: FBType };
		const res = await httpRequest.Post('/crm/query_dev_flow_fb_define.action', {}, data);
		if (!(res.code === '0000') && !res.success) {
			ElMessage({
				type: 'error',
				message: '查询功能块失败',
				duration: BASE_API.MSG_SHOW_TIME,
			});
			return [];
		} else {
			const records = res.Records || [];
			return records;
		}
	};
	const toFBDataTransTreeData = (data: any[]) => {
		const newData: any[] = [];
		if (data.length) {
			data.forEach((item) => {
				const params = {
					FBName: item.FBName,
					Descption: item.Descption,
					Lang: item.Lang,
					InputVars: item.InputVars,
					OutputVars: item.OutputVars,
					Remarks: item.Remarks,
				};
				const index = newData.findIndex((d) => d.SubType === item.SubType);
				if (index !== -1) {
					newData[index].children.push(params);
				} else {
					newData.push({ Descption: item.TypeName, SubType: item.SubType, children: [params] });
				}
			});
		}

		return newData;
	};

	const handleShowflowFun = () => {
		state.flowFunPiece = !state.flowFunPiece;
	};
	// 弹窗里添加流程功能块触发
	const handleAddFlowPiece = () => {
		addFlowPieceRef.value?.validate((valid) => {
			if (!valid) {
				ElMessage({
					type: 'warning',
					message: '请填写必传字段',
					duration: BASE_API.MSG_SHOW_TIME,
				});

				return;
			}
			console.log('nodeTypeList', nodeTypeList);
			console.log('提交', state.addFlowPieceData);
			// return;
			const data = {
				FBName: state.addFlowPieceData.FBName,
				Descption: state.addFlowPieceData.Descption,
				FBType: 2,
				FlowID: routeParams.FlowID,
				Lang: state.addFlowPieceData.Lang,
				InputVars: state.addFlowPieceData.InputVars,
				OutputVars: state.addFlowPieceData.OutputVars,
				Remarks: state.addFlowPieceData.Remarks,
			};
			httpRequest.Post('/crm/add_dev_flow_fb_define.action', {}, data).then((res) => {
				if (res.code === '0000' && res.success) {
					ElMessage({
						type: 'success',
						message: '添加功能块成功',
						duration: BASE_API.MSG_SHOW_TIME,
					});
					const item = {
						FBName: data.FBName,
						class: 'big-rectangle',
						Descption: data.Descption,
						id: data.FBName,
						InputVars: data.InputVars,
						OutputVars: data.OutputVars,
						Lang: data.Lang,
						Remarks: data.Remarks,
					};

					nodeTypeList.value.push(item);
				} else {
					ElMessage({
						type: 'error',
						message: '添加功能块失败',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				}
				state.addFlowPiecedialog = false;
			});
			state.addFlowPieceData = {};
		});
	};
	return {
		...toRefs(state),
		leftNavRef,
		startEndFbRef,
		addFlowPieceRef,
		initSortable,
		handleQueryFlowPiece,
		toFBDataTransTreeData,
		handleShowflowFun,
		handleAddFlowPiece,
	};
}
